from flask import g, Blueprint, request, jsonify, render_template, session, redirect

from common import Result
from forms import AnswerForm
from models import Classes, TestPaper, TestPaperAnswer, QuestionAnswer, SingleChoiceQuestion, JudgmentalQuestion, \
    ShortAnswerQuestion, BaseQuestion
from exts import db, get_time
from sqlalchemy import and_
from flask_login import login_required
from decorations import student_required

bp = Blueprint("api_student", __name__, url_prefix="/api/student")


# todo before_request
@bp.before_request
@login_required
@student_required
def before_request():
    pass


# todo /answer 提交答案接口
@bp.route("/answer", methods=["POST"])
def answer():
    answer_list = eval(session["answer_list"])
    data = eval(request.form.get("data"))
    question_type = data["question_type"]

    # 对多选题进行答案格式化处理
    if int(question_type) == 3:
        choice = ["a", "b", "c", "d"]
        my_answer = ""
        for i in choice:
            if i in data:
                my_answer += i + '&'
        if len(my_answer) == 0:
            return Result.error(
                msg="答案不能为空 !",
                code=2
            )
        my_answer = my_answer[:-1]
    else:
        # my_answer = data["my_answer"]
        af = AnswerForm(**data)
        if not af.validate():
            errors = ""
            for i in af.errors:
                errors += af.errors[i][0]
                break
            return Result.error(
                msg=errors,
                code=2
            )
        my_answer = af.my_answer.data
    question_id = data["question_id"]
    # print(question_type, my_answer, question_id)

    # 答案缓存，记录学生已经完成的答题，缓存到session，与判题无关
    my_answer_ = None
    if my_answer == "1":
        my_answer_ = "对"
    elif my_answer == "0":
        my_answer_ = "错"
    elif len(my_answer) == 1:
        my_answer_ = my_answer.upper()
    elif str(question_type) == str(3):
        my_answer_ = list(my_answer.upper().split("&"))
    else:
        my_answer_ = my_answer
    answer_list[int(session["all_question_count"])] = my_answer_
    session["answer_list"] = str(answer_list)

    # 判断对错
    base_question = db.session.query(BaseQuestion).get(question_id)
    if base_question.question_type == 0:
        true_or_false = 1 if str(base_question.single_choice_question.answer).replace(" ", "") == str(my_answer).replace(" ", "") else 0
        # print(base_question.single_choice_question.answer)
        # print(my_answer)
        # print(true_or_false)
    elif base_question.question_type == 1:
        true_or_false = 1 if int(base_question.judgmental_question.answer) == int(my_answer) else 0
    elif base_question.question_type == 2:
        true_or_false = 1 if base_question.short_answer_question.answer == my_answer else 0
    elif base_question.question_type == 3:
        true_or_false = 1 if base_question.multiple_choice_question.answer == my_answer else 0
    elif base_question.question_type == 4:
        true_or_false = 1 if base_question.picture_question.answer == my_answer else 0

    id_test_paper = session.get("id_test_paper")
    # 查看学生是否已经作答过，是否产生了试卷
    test_paper_answer = db.session.query(TestPaperAnswer).filter(and_(
        TestPaperAnswer.id_student == g.user.student.id,
        TestPaperAnswer.id_test_paper == id_test_paper
    )).first()

    if test_paper_answer is None:
        test_paper_answer = TestPaperAnswer(
            score=0,
            create_time=get_time(),
            update_time=get_time(),
            is_delete=0,
            test_paper=db.session.query(TestPaper).filter(TestPaper.id == id_test_paper).first(),
            student=g.user.student,
            status=0
        )

    # 查看这道题该学生是否作答过
    question_answer = db.session.query(QuestionAnswer).filter(and_(
        QuestionAnswer.id_test_paper_answer == test_paper_answer.id,
        QuestionAnswer.id_base_question == base_question.id
    )).first()
    if question_answer is None:
        question_answer = QuestionAnswer(
            my_answer=my_answer,
            true_or_false=true_or_false,
            create_time=get_time(),
            update_time=get_time(),
            is_delete=0,
            test_paper_answer=test_paper_answer,
            base_question=base_question
        )
    else:
        question_answer.my_answer = my_answer,
        question_answer.true_or_false = true_or_false
        question_answer.update_time = get_time()

    db.session.add(question_answer)
    db.session.commit()

    session["all_question_count"] = session.get("all_question_count") + 1
    if session.get("len_all_question") == session.get("all_question_count"):
        session["all_question_count"] = session.get("all_question_count") - 1
        return Result.error(
            msg="试卷已经答完"
        )
    else:
        return Result.success(
            msg="下一题"
        )


# todo /submit_papers 交卷
@bp.route("/submit_papers", methods=["GET"])
def submit_papers():
    id_test_paper = session.get("id_test_paper")
    test_paper_answer = db.session.query(TestPaperAnswer).filter(
        and_(TestPaperAnswer.id_student == g.user.student.id, TestPaperAnswer.id_test_paper == id_test_paper)).first()
    question_answer_s = db.session.query(QuestionAnswer).filter(
        QuestionAnswer.id_test_paper_answer == test_paper_answer.id).all()
    true_count = 0
    for question_answer in question_answer_s:
        if question_answer.true_or_false == 1:
            true_count += 1

    # print(str(true_count/len(question_answer_s)))
    test_paper_answer.score = str(100 * true_count / len(question_answer_s))
    test_paper_answer.status = 1  # 完成交卷

    db.session.commit()

    return Result.success(
        msg="已经交卷"
    )
